import Router from 'koa-router'
import axios from './utils/axios'

import Redis from 'koa-redis'
import nodeMailer from 'nodemailer'
import mongoUser from '../dbs/models/users'
import Passport from './utils/passport'

import Email from '../dbs/config'

let redis_store = new Redis().client
let router = new Router({
  prefix: '/users'
})
//-------------------------        发送验证码         -------------------------------------
router.post('/verify', async (ctx, next) => {
  let username = ctx.request.body.username
  let email = ctx.request.body.email

  const saveExpire = await redis_store.hget(`nodemail:${username}`, 'expire')
  if (saveExpire && new Date().getTime() < saveExpire)
    return (ctx.body = { code: -1, msg: '验证请求过于频繁，1分钟之后再试' })

  //发送邮件 调用nodeMailer创建发送邮件的实例对象
  let transporter = nodeMailer.createTransport({
    service: 'qq',
    auth: {
      user: Email.smtp.user,
      pass: Email.smtp.pass
    }
  })
  let ko = {
    code: Email.smtp.code(),
    expire: Email.smtp.codeExpire(),
    email: email,
    user: username
  }
  let mailOptions = {
    from: `"认证邮件" <${Email.smtp.user}>`,
    to: ko.email,
    subject: '《Kim高仿美团网全栈实战》注册码',
    html: `您在《Kim高仿美团网全栈实战》课程中注册，您的邀请码是${ko.code}`
  }
  await transporter.sendMail(mailOptions, (error, info) => {
    if (error) return console.log(error)
    redis_store.hmset(
      `nodemail:${ko.user}`,
      'code',
      ko.code,
      'expire',
      ko.expire,
      'email',
      ko.email
    )
  })
  ctx.body = { code: 0, msg: '验证码已发送，可能会有延时，有效期1分钟' }
})
//-------------------------        注册         -------------------------------------

router.post('/signup', async ctx => {
  const { username, password, email, code } = ctx.request.body

  if (!code) return (ctx.body = { code: -1, msg: '无验证' })

  const saveCode = await redis_store.hget(`nodemail:${username}`, 'code')
  const saveExpire = await redis_store.hget(`nodemail:${username}`, 'expire')

  if (code !== saveCode)
    return (ctx.body = { code: -1, msg: '请填写正确的验证码' })
  if (new Date().getTime() > saveExpire)
    return (ctx.body = { code: -1, msg: '验证码已过期，请重新尝试' })

  let user = await mongoUser.find({ username })
  if (user.length)
    return (ctx.body = { code: -1, msg: '该账户已经被注册，请重新注册' })
  let nuser = await mongoUser.create({ username, password, email })
  if (!nuser) return (ctx.body = { code: -1, msg: '注册失败' })

  let res = await axios.post('/users/signin', { username, password }) //先请求登陆的接口
  if (res.data && res.data.code === 0)
    return (ctx.body = { code: 0, msg: `注册成功`, user: res.data.user })
  ctx.body = { code: -1, msg: 'error' }
})
//-------------------------        登陆,并保留登陆状态         -------------------------------------
router.post('/signin', async (ctx, next) => {
  return Passport.authenticate('local', function(err, user, info, status) {
    if (err) return (ctx.body = { code: -1, msg: '登陆失败' })
    if (!user) return (ctx.body = { code: 1, msg: info })
    ctx.body = { code: 0, msg: '登录成功', user }
    return ctx.login(user)
  })(ctx, next)
})
//-------------------------         登出         -------------------------------------
router.get('/exit', async (ctx, next) => {
  await ctx.logout()
  if (!ctx.isAuthenticated()) return (ctx.body = { code: 0 }) //如果不是登陆状态，返回code:0，
  ctx.body = { code: -1 }
})
//-------------------------        获得登陆用户名         -------------------------------------
router.get('/getUser', async ctx => {
  if (!ctx.isAuthenticated()) return (ctx.body = { user: '', email: '' }) //如果不是登陆状态，返user: '', email: '' ，
  const { username, email } = ctx.session.passport.user
  return (ctx.body = { user: username, email })
})

export default router
